package in.edupack.hibernate.dao;

import in.edupack.hibernate.pojo.Student;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class StudentDAO {
  public static void main(String[] args) {
	  StudentDAO studentDAO = new StudentDAO();
	  //studentDAO.simpleInsert();
	  //studentDAO.simpleUpdate();
	  studentDAO.simpleDelete();
	  
	
}	

  /**
   * This method demonstrate a simple database insertion using Hibernate 
   */
  public void simpleInsert()
  {
	    Session session = null;		
		SessionFactory sessionFactory = new Configuration().configure("in/edupack/hibernate/config/hbm-config.xml").buildSessionFactory();
		session = sessionFactory.openSession();
		Transaction txn = session.beginTransaction();
		
		Student student = new Student();
		student.setId(5);
		student.setName("titu");
		student.setAge(25);
		student.setAddress("jajpur");
		student.setPhone("9438423490");
		
		try{
	    session.save(student);
	    
     	}catch(Exception e){e.printStackTrace();}
		
	    //Data saved here in session
     	//session.flush(); 
		txn.commit();
		session.close();
		
		System.out.println("Success !!");
  }
  
  public void simpleUpdate()
  {
	    Session session = null;		
		SessionFactory sessionFactory = new Configuration().configure("in/edupack/hibernate/config/hbm-config.xml").buildSessionFactory();
		session = sessionFactory.openSession();
		Transaction txn = session.beginTransaction();
		
		Student student = (Student) session.get(Student.class, new Long(1));
		
		student.setAddress("usa");
		
		session.save(student);
		
		txn.commit();
		session.close();
		
		System.out.println("Record Updated Successfully ");
  }
  
  public void simpleDelete()
  {
	  
	    Session session = null;		
		SessionFactory sessionFactory = new Configuration().configure("in/edupack/hibernate/config/hbm-config.xml").buildSessionFactory();
		session = sessionFactory.openSession();
		Transaction txn = session.beginTransaction();
		
		String hql = "delete from Student where id = 2";
		
		Query query = session.createQuery(hql);
		int row = query.executeUpdate();
		
		if (row != 0)
			 System.out.println("Record Deleted Successfully....");
		
		txn.commit();
		session.close();
	  
  }
  
}
